package com.wframe.project.jnd.extinterface.sms;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.frame.database.JdataBean;
import com.wframe.framework.spring.SpringContextHolder;
import com.wframe.project.jnd.services.CommonService;

public class SmsUtil {

    @Autowired
    private CommonService commonService;

    /**
     * 发送采购计划提醒
     *
     * @param username
     * @param mobile
     * @param remindname
     * @param remindcon
     */
    public void sendPurchaseRemind(String mobile, String username, String remindname, String remindcon) {
        String temp = SmsConfig.getConfig().getRemindplan();
        String content = temp.replaceAll("\\$\\{uname}", username).replaceAll("\\$\\{remindname}", remindname).replaceAll("\\$\\{remindcon}", remindcon);
        sendSms(mobile, content);
    }

    /**
     * 发送注册验证码短信
     *
     * @param mobile
     * @throws Exception
     */
    public void sendRegCode(String mobile) throws Exception {
        String temp = SmsConfig.getConfig().getRegtemp();
        String code = createSmsCode(mobile, 5);
        String content = temp.replaceAll("\\$\\{code\\}", code);
        sendSms(mobile, content);
    }

    /**
     * 发送修改手机号验证码
     *
     * @param mobile
     * @throws Exception
     */
    public void sendChangephoneCode(String mobile) throws Exception {
        String temp = SmsConfig.getConfig().getChangetemp();
        String code = createSmsCode(mobile, 5);
        String content = temp.replaceAll("\\$\\{code\\}", code);
        sendSms(mobile, content);
    }

    /**
     * 发送找回密码验证码
     *
     * @param mobile
     * @throws Exception
     */
    public void sendFindCode(String mobile) throws Exception {
        String temp = SmsConfig.getConfig().getFindtemp();
        String code = createSmsCode(mobile, 5);
        String content = temp.replaceAll("\\$\\{code\\}", code);
        sendSms(mobile, content);
    }

    public void sendOrderShip(String mobile, String ordercode, String username) {
        String temp = SmsConfig.getConfig().getOrdership();
        String content = temp.replaceAll("\\$\\{uname\\}", username);
        content = content.replaceAll("\\$\\{ordercode\\}", ordercode);
        sendSms(mobile, content);
    }

    public void sendApproveSuccess(String mobile, String username) {
        String temp = SmsConfig.getConfig().getApprovesuccess();
        String content = temp.replaceAll("\\$\\{uname\\}", username);
        sendSms(mobile, content);
    }

    public void sendApproveFailure(String mobile, String username) {
        String temp = SmsConfig.getConfig().getApprovefailure();
        String content = temp.replaceAll("\\$\\{uname\\}", username);
        sendSms(mobile, content);
    }

    public void sendSms(String mobile, String content) {
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost post = new HttpPost(SmsConfig.getConfig().getApiurl());
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", SmsConfig.getConfig().getUsername()));
            params.add(new BasicNameValuePair("passwd", SmsConfig.getConfig().getPasswd()));
            params.add(new BasicNameValuePair("phone", "{\"params\":[{\"mobile\":\"" + mobile + "\"}]}"));
            params.add(new BasicNameValuePair("msg", content + SmsConfig.getConfig().getSign()));
            params.add(new BasicNameValuePair("needstatus", "false"));
            post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
            HttpResponse response = httpclient.execute(post);
            HttpEntity entitys = response.getEntity();
            if (entitys != null) {
                String restr = EntityUtils.toString(entitys);
                System.out.println(restr);
                JSONObject json = JSON.parseObject(restr);
                if (!"0".equals(json.getString("respcode"))) throw new Exception(restr);

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Logger.getLogger(SmsUtil.class).error("短信发送失败", e);
        }
    }

    public String createSmsCode(String mobile, int size) throws Exception {
        String code = "";
        Random random = new Random();
        for (int i = 1; i <= size; i++) {
            code += random.nextInt(9);
        }
        commonService = SpringContextHolder.getBean(CommonService.class);
        commonService.saveSmsCode(mobile, code);
        return code;
    }

    public boolean smsCheck(String mobile, String code) {
        commonService = SpringContextHolder.getBean(CommonService.class);
        JdataBean bean = commonService.getSmsCode(mobile);
        boolean check = false;
        if (bean != null && bean.getString("checknum").equals(code) && bean.getInt("ischeck") == 0) {
            Date time = (Date) bean.get("sendtime");
            Long diff = new Date().getTime() - time.getTime();
            diff = diff / 1000;
            if (diff.intValue() <= SmsConfig.SmsLimit) check = true;
        }
        return check;
    }

    public void removeSmsCode(String mobile) {
        commonService = SpringContextHolder.getBean(CommonService.class);
        commonService.updateSmsCode(mobile, true);
    }

}
